package com.lb.rabbitmq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

public class RabbitMQConsumer {
    private static final String QUEUE_NAME = "example_queue";

    public static void main(String[] args) {
        // 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost"); // RabbitMQ 服务器地址
        factory.setUsername("guest"); // 用户名
        factory.setPassword("guest"); // 密码

        try (
            // 创建连接和信道
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel()
        ) {
            // 声明队列（确保队列存在）
            channel.queueDeclare(QUEUE_NAME, true, false, false, null);

            // 消费消息
            DeliverCallback deliverCallback = (consumerTag, delivery) -> {
                String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
                System.out.println("Message received: " + message);

                // 消息处理完后手动确认
//                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            };
            CancelCallback cancelCallback = consumerTag -> System.out.println("Cancelled: " + consumerTag);

            // 开始消费
            System.out.println("Waiting for messages...");
//            channel.basicQos(0,1,false);
            channel.basicConsume(QUEUE_NAME, true, deliverCallback, cancelCallback);

        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        }
    }
}
